﻿namespace Chain.Wechat
{
    using Chain.BLL;
    using Chain.Common.DEncrypt;
    using Chain.Model;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Drawing.Imaging;
    using System.Text;
    using System.Web;
    using Web.Common;

    public class BusinessLogic
    {
        public void DrawImage(Chain.Model.Mem member)
        {
            this.DrawImage(member, "~/Upload/WeiXin/Images/bg.jpg", "~/Upload/WeiXin/Images/" + member.MemWeiXinCard + ".jpg");
            this.DrawImage(member, "~/Upload/WeiXin/Images/memCard.jpg", "~/Upload/WeiXin/Images/" + member.MemCard + "-MemCard.jpg");
        }

        public void DrawImage(Chain.Model.Mem member, string sourceUrl, string targetUrl)
        {
            Bitmap smallWeiXin = new Bitmap(130, 130);
            Image weixinImg = QRCodeImage.CreateQRCode(member.MemCard);
            Graphics.FromImage(smallWeiXin).DrawImage(weixinImg, new Point(-35, -35));
            string savePath = HttpContext.Current.Server.MapPath(targetUrl);
            Bitmap bigWeiXin = new Bitmap(200, 200);
            Graphics.FromImage(bigWeiXin).DrawImage(smallWeiXin, new Rectangle(0, 0, 200, 200), new Rectangle(0, 0, 130, 130), GraphicsUnit.Pixel);
            Image bgImg = Image.FromFile(HttpContext.Current.Server.MapPath(sourceUrl), true);
            Bitmap bmp = new Bitmap(bgImg.Width, bgImg.Height, PixelFormat.Format32bppArgb);
            Graphics g = Graphics.FromImage(bmp);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.DrawImage(bgImg, new Rectangle(0, 0, bgImg.Width, bgImg.Height), new Rectangle(0, 0, bgImg.Width, bgImg.Height), GraphicsUnit.Pixel);
            g.DrawImage(bigWeiXin, new RectangleF(50f, 60f, 200f, 200f), new RectangleF(0f, 0f, 200f, 200f), GraphicsUnit.Pixel);
            g.DrawString("NO:" + member.MemCard, new Font("微软雅黑", 34f, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.White, new PointF(280f, 70f));
            g.DrawString("积分:" + member.MemPoint, new Font("微软雅黑", 30f, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.White, new PointF(280f, 115f));
            g.DrawString("余额:" + member.MemMoney.ToString("F2"), new Font("微软雅黑", 30f, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.White, new PointF(280f, 160f));
            string pastStr = (member.MemPastTime.ToString("yyyy-MM-dd") == "2900-01-01") ? "有效期:永久有效" : ("有效期:" + member.MemPastTime.ToString("yyyy-MM-dd"));
            g.DrawString(pastStr, new Font("微软雅黑", 30f, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.White, new PointF(280f, 205f));
            bmp.Save(savePath, ImageFormat.Jpeg);
        }

        public string GetMemCardResponse(IRequest req, Chain.Model.Mem mem, string title)
        {
            this.DrawImage(mem);
            Chain.Model.SysParameter modelSysPara = new Chain.BLL.SysParameter().GetModel(1);
            if (string.IsNullOrEmpty(title))
            {
                title = string.Format("您的{0}微信会员卡", modelSysPara.WeiXinShopName);
            }
            string imageUrl = string.Format("http://{0}/Upload/WeiXin/Images/{1}.jpg?random={2}", modelSysPara.SystemDomain, mem.MemWeiXinCard, Guid.NewGuid());
            string url = string.Format("http://{0}/ReceptionPage/index.aspx?MemWeiXinCard={1}&random={2}", modelSysPara.SystemDomain, mem.MemWeiXinCard, Guid.NewGuid());
            NewsResponseItem item = new NewsResponseItem(title, "", imageUrl, url);
            List<NewsResponseItem> list = new List<NewsResponseItem>();
            list.Add(item);
            return new NewsResponse(req, list).Result();
        }

        public string GetResponseByRule(IRequest req, string content)
        {
            Chain.Model.WeiXinRule ruleModel = new Chain.BLL.WeiXinRule().GetModelByNewsRuleID(content);
            if (ruleModel != null)
            {
                if (ruleModel.RuleNewsType == "text")
                {
                    return new TextResponse(req, ruleModel.RuleContent).Result();
                }
                if (ruleModel.RuleNewsType == "news")
                {
                    List<Chain.Model.WeiXinNews> newsList = new Chain.BLL.WeiXinNews().GetModelList("NewsRuleID=" + ruleModel.RuleID);
                    List<NewsResponseItem> list = new List<NewsResponseItem>();
                    foreach (Chain.Model.WeiXinNews newsRule in newsList)
                    {
                        NewsResponseItem item = new NewsResponseItem(newsRule.NewsTitle, newsRule.NewsDesc, newsRule.NewsUrlFirst, newsRule.NewsUrlSecond);
                        list.Add(item);
                    }
                    return new NewsResponse(req, list).Result();
                }
            }
            return string.Empty;
        }

        public string GetWelcomeText()
        {
            StringBuilder temp = new StringBuilder();
            Chain.Model.SysParameter modelSysPara = new Chain.BLL.SysParameter().GetModel(1);
            Chain.BLL.WeiXinRule bll = new Chain.BLL.WeiXinRule();
            temp.Append("\n" + modelSysPara.WeiXinSalutatory + "\n");
            temp.Append("回复\"会员\" 申请/出示会员卡\n");
            temp.Append("回复\"绑定\" 已有会员转微信会员卡\n");
            temp.Append("回复\"签到\" 进行会员签到并获得积分\n");
            foreach (DataRow row in bll.Attention().Rows)
            {
                temp.Append(row["RuleDesc"].ToString() + "\n");
            }
            return temp.ToString();
        }

        public int MemRegister(string mobile, string openID)
        {
            Chain.Model.Mem model = new Chain.Model.Mem();
            model.MemCard = mobile;
            string pwd = mobile.Substring(5, 6);
            model.MemPassword = DESEncrypt.Encrypt(pwd);
            model.MemName = "";
            model.MemSex = true;
            model.MemIdentityCard = "";
            model.MemMobile = mobile;
            model.MemPhoto = "";
            model.MemBirthdayType = true;
            model.MemBirthday = Convert.ToDateTime("1900-1-1 0:00:00");
            model.MemIsPast = false;
            model.MemPastTime = Convert.ToDateTime("2900-1-1 0:00:00");
            model.MemPoint = 0;
            model.MemPointAutomatic = true;
            model.MemMoney = 0M;
            model.MemEmail = "";
            model.MemAddress = "";
            model.MemState = 0;
            model.MemRecommendID = 0;
            model.MemLevelID = 0;
            Chain.Model.MicroWebsiteSceneStr websitescenestr = new Chain.Model.MicroWebsiteSceneStr();
            websitescenestr = new Chain.BLL.MicroWebsiteSceneStr().GetModel(openID);
            if (websitescenestr != null)
            {
                model.MemShopID = websitescenestr.SceneStr;
            }
            else
            {
                model.MemShopID = 1;
            }
            model.MemWeiXinCards = openID;
            model.MemAttention = 1;
            model.MemCreateTime = DateTime.Now;
            model.MemRemark = "";
            model.MemUserID = 1;
            model.MemTelePhone = "";
            model.MemWeiXinCard = openID;
            model.MemQRCode = "";
            model.MemProvince = "";
            model.MemCity = "";
            model.MemCounty = "";
            model.MemVillage = "";
            return new Chain.BLL.Mem().Add(model);
        }

        public int MemSign(Chain.Model.Mem member)
        {
            Chain.BLL.PointLog bllPoint = new Chain.BLL.PointLog();
            Chain.Model.SysParameter modelSysPara = new Chain.BLL.SysParameter().GetModel(1);
            if (member == null)
            {
                return -1;
            }
            if (modelSysPara.SignInPoint <= 0)
            {
                return -2;
            }
            if (bllPoint.IsSignedToday(member.MemID))
            {
                return -3;
            }
            Chain.Model.PointLog model = new Chain.Model.PointLog();
            model.PointMemID = member.MemID;
            model.PointNumber = modelSysPara.SignInPoint;
            model.PointChangeType = 0x10;
            model.PointRemark = "会员微信签到送积分";
            model.PointShopID = member.MemShopID;
            model.PointCreateTime = DateTime.Now;
            model.PointUserID = member.MemUserID;
            model.PointOrderCode = "";
            bllPoint.Add(model);
            Chain.BLL.SysParameter bllSysParameter = new Chain.BLL.SysParameter();
            if (bllSysParameter.GetModel(1).ShopPointManage)
            {
                this.SetShopPoint(member.MemUserID, member.MemShopID, modelSysPara.SignInPoint, string.Format("会员：{0} 微信签到送积分,扣除{1}", member.MemCard, modelSysPara.SignInPoint), 1, true);
            }
            return new Chain.BLL.Mem().UpdatePoint(member.MemID, modelSysPara.SignInPoint);
        }

        public void SetShopPoint(int UserID, int ShopID, int Point, string Remark, int Type, bool isPointSame)
        {
            if ((Point != 0) && (ShopID > 1))
            {
                Chain.BLL.SysShop bllSysShop = new Chain.BLL.SysShop();
                Chain.Model.SysShop mdSysShop = new Chain.Model.SysShop();
                mdSysShop = bllSysShop.GetModel(ShopID);
                if (isPointSame && ((mdSysShop.PointType != 1) || (Point <= mdSysShop.PointCount)))
                {
                    mdSysShop.PointCount -= Point;
                    bllSysShop.Update(mdSysShop);
                    Chain.BLL.SysShopPointLog bllSysShopPointLog = new Chain.BLL.SysShopPointLog();
                    Chain.Model.SysShopPointLog mdSysShopPointLog = new Chain.Model.SysShopPointLog();
                    mdSysShopPointLog.Count = -1 * Point;
                    mdSysShopPointLog.CreateTime = DateTime.Now;
                    mdSysShopPointLog.OutShopID = ShopID;
                    mdSysShopPointLog.ShopID = ShopID;
                    mdSysShopPointLog.ShopPointAccount = "JF" + DateTime.Now.ToString("yyMMddHHmmssffff");
                    mdSysShopPointLog.ShopPointType = Type;
                    mdSysShopPointLog.UserID = UserID;
                    mdSysShopPointLog.Remark = Remark;
                    bllSysShopPointLog.Add(mdSysShopPointLog);
                }
            }
        }
    }
}

